/*
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 * 02111-1307, USA.
 *
 * http://www.gnu.org/copyleft/gpl.html
 */

package l1j.server.server.clientpackets;

import java.util.logging.Level;
import java.util.logging.Logger;

import l1j.opqlo.Server.L1World.L1World;
import l1j.server.echo.ClientThread;
import l1j.server.server.datatables.lock.ClanEmblemReading;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.serverpackets.S_Emblem;
import l1j.server.server.serverpackets.S_ServerMessage;
import l1j.server.server.templates.L1EmblemIcon;

// Referenced classes of package l1j.server.server.clientpackets:
// ClientBasePacket

public class C_Emblem extends ClientBasePacket {

	private static final String C_EMBLEM = "[C] C_Emblem";
	private static Logger _log = Logger.getLogger(C_Emblem.class.getName());

	@Override
	public String getType() {
		return C_EMBLEM;
	}

	@Override
	public void start(final byte[] decrypt, final ClientThread client) {
		try {
			// 資料載入
			this.read(decrypt);

			final L1PcInstance pc = client.getActiveChar();
			if (pc.isGhost()) { // 鬼魂模式
				return;
			}

			if (pc.isDead()) { // 死亡
				return;
			}

			if (pc.isTeleport()) { // 傳送中
				return;
			}

			final int clan_id = pc.getClanid();
			if (clan_id != 0) {
				if (pc.getClan().getLeaderId() != pc.getId()) {
					// 219 \f1王子或公主才能上傳徽章。
					pc.sendPackets(new S_ServerMessage(219));
					return;
				}

				final byte[] iconByte = this.readByte();
				//System.out.println(iconByte + " length:" + iconByte.length + " clan_id:" + clan_id);
				L1EmblemIcon emblemIcon = ClanEmblemReading.get().get(clan_id);

				if (emblemIcon != null) {
					//System.out.println("update");
					emblemIcon.set_clanIcon(iconByte);
					emblemIcon.set_update(emblemIcon.get_update() + 1);
					ClanEmblemReading.get().updateClanIcon(emblemIcon);

				} else {
					//System.out.println("NEW");
					emblemIcon = ClanEmblemReading.get().storeClanIcon(clan_id, iconByte);
				}

				//player.sendPackets(new S_Emblem(emblemIcon));
				L1World.getInstance().broadcastPacketToAll(new S_Emblem(emblemIcon));
			}
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);

		} finally {
			this.over();
		}
	}
}
